package com.zsule.controllers.front;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zsule.constants.CoreConstant;
import com.zsule.controllers.BaseController;
import com.zsule.controllers.websocket.ClientInfo;
import com.zsule.controllers.websocket.UserSessionCache;
import com.zsule.entity.EShop;
import com.zsule.entity.EUser;
import com.zsule.entity.EUserAddress;
import com.zsule.entity.PageEntity;
import com.zsule.entity.Shipping;
import com.zsule.entity.ShopAndGoods;
import com.zsule.service.IShopGoodsService;
import com.zsule.service.IShopService;
import com.zsule.service.IShoppingService;
import com.zsule.service.IUserAddressService;
import com.zsule.service.IUserService;

@Controller
public class EshopController extends BaseController {

	private static final Logger logger = Logger.getLogger(EUserController.class);

	@Autowired
	private IUserService euserService;

	@Autowired
	private IShopService eshopService;

	@Autowired
	private IShopGoodsService shopAndGoodsService;
	
	@Autowired
	private IUserAddressService euserAddressService;

	
	@Autowired
	private IShoppingService shippingService;

	@RequestMapping(value={"","/","/index"})
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("index.httl");
		EUser user = (EUser) this.getSessionAttribute(request,CoreConstant.USER_SESSION_NAME);
		if(user!=null){
			mav.addObject("user", user);
			List<EUserAddress> addressList = euserAddressService.getAddressByUserId(user.getId());
			mav.addObject("addressList", addressList);
		}else{
			String userId = this.getUserIdFromCookie(request);
			if(userId!=null){
				user = euserService.findById(userId);
				if(user!=null){
					List<EUserAddress> addressList = euserAddressService.getAddressByUserId(user.getId());
					mav.addObject("addressList", addressList);
				}
			}
		}
		return mav;
	}
	@RequestMapping(value="/shop/build",method=RequestMethod.GET)
	public ModelAndView startShop(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("startShop.httl");
		EUser user = (EUser) this.getSessionAttribute(request,
				CoreConstant.USER_SESSION_NAME);
		if (user == null) {
			return new ModelAndView("redirect:/login");
		}
		mav.addObject("user", user);
		return mav;
	}
//	@RequestMapping("/shop/{id}")
//	public ModelAndView enterShop(@PathVariable("id") String shopId, HttpServletRequest request) {
//		ModelAndView mav = new ModelAndView("/shop.httl");
//		setVar(mav);
//		try {
//			EUser user = (EUser) this.getSessionAttribute(request,
//					CoreConstant.USER_SESSION_NAME);
//			if (user == null) {
//				mav.setViewName("redirect:/login");
//				return mav;
//			}
//			EShop shop = eshopService.getEShopByUser(shopId);
//			PageEntity page = new PageEntity();
//			this.setPage(page);
//			this.getPage().setPageSize(20);
//			ShopAndGoods query = new ShopAndGoods();
//			query.setStatus(1);
//			List<ShopAndGoods> list = shopAndGoodsService.getShopperGoods(shopId, query, page);
//			List<Shipping> shippingList = shippingService.getShippingByUser(shopId);
//			mav.addObject("query", query);
//			mav.addObject("shopperGoods", list);
//			mav.addObject("page", this.getPage());
//			mav.addObject("user", user);
//			mav.addObject("shop", shop);
//			mav.addObject("shippingList", shippingList);
//		} catch (Exception e) {
//			logger.error("EshopController.enterShop", e);
//		}
//		return mav;
//	}
	@RequestMapping("/shop/{shopId}/enter")
	public ModelAndView listGoods(@PathVariable("shopId") String shopId,HttpServletRequest request,HttpServletResponse response, ShopAndGoods query,
			@ModelAttribute("page") PageEntity page) {
		ModelAndView modelAndView = new ModelAndView("/shop.httl");
		try {
			EUser user = (EUser) this.getSessionAttribute(request,
					CoreConstant.USER_SESSION_NAME);
			EShop shop = eshopService.getEShopByUser(shopId);
			this.setPage(page);
			this.getPage().setPageSize(20);
			query.setStatus(1);
			List<ShopAndGoods> list = shopAndGoodsService.getShopperGoods(
					shopId, query, page);
			List<Shipping> shippingList = shippingService.getShippingByUser(shopId);
			modelAndView.addObject("query", query);
			modelAndView.addObject("shopperGoods", list);
			modelAndView.addObject("page", this.getPage());
			modelAndView.addObject("shop", shop);
			modelAndView.addObject("user", user);
			modelAndView.addObject("shippingList", shippingList);
		} catch (Exception e) {
			logger.error("EshopController.listGoods", e);
		}

		return modelAndView;
	}
	@ResponseBody
	@RequestMapping(value = "/shop/build", method = RequestMethod.POST)
	public ModelAndView startShop(EShop eshop, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("redirect:/goods/add");
		try {
			EUser user = (EUser) this.getSessionAttribute(request,CoreConstant.USER_SESSION_NAME);
			if (user == null) {
				return new ModelAndView("redirect:/login");
			}
			modelAndView.addObject("user", user);
			user.setIsShopper(1);
			user.setShopName(eshop.getShopName());
			euserService.updateEUserShopper(user);
			eshop.setRegTime(new Date());
			eshopService.insert(eshop);
		} catch (Exception e) {
			logger.error("EshopController.insert", e);
		}
		return modelAndView;
	}
	
	@RequestMapping("/shop/detail")
	public ModelAndView shopManage(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("/euser/shopinfo.httl");
		EUser user = (EUser) this.getSessionAttribute(request,
				CoreConstant.USER_SESSION_NAME);
		if (user == null) {
			mav.setViewName("redirect:/login");
			return mav;
		}
		EShop eshop = eshopService.getEShopByUser(user.getId());
		List<Shipping> shippings = shippingService.getShippingByUser(user
				.getId());
		mav.addObject("user", user);
		mav.addObject("eshop", eshop);
		mav.addObject("shippings", shippings);
		mav.addObject("leaf", "detail");
		return mav;
	}

	@RequestMapping(value = "/shop/save", method = RequestMethod.POST)
	public ModelAndView saveEShop(EShop eshop, HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView(
				"redirect:/shop/detail");
		try {
			eshopService.updateByObj(eshop);
			// eshopService.save(eshop);
		} catch (Exception e) {
			logger.error("EUserController.saveEShop", e);
		}
		return modelAndView;
	}

	@RequestMapping(value = "/shop/shipping/delete", method = RequestMethod.POST)
	public ModelAndView deleteShipping(Shipping shipping,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView(
				"redirect:/shop/detail");
		try {
			// eshopService.updateByObj(eshop);
			shippingService.remove(shipping);
		} catch (Exception e) {
			logger.error("EUserController.updateShipping", e);
		}
		return modelAndView;
	}

	@RequestMapping(value = "/shop/shipping/update", method = RequestMethod.POST)
	public ModelAndView updateShipping(Shipping shipping,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView(
				"redirect:/shop/detail");
		try {
			// eshopService.updateByObj(eshop);
			shippingService.save(shipping);
		} catch (Exception e) {
			logger.error("EUserController.updateShipping", e);
		}
		return modelAndView;
	}

	@RequestMapping(value = "/shop/shipping/save", method = RequestMethod.POST)
	public ModelAndView saveShipping(Shipping shipping,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView(
				"redirect:/shop/detail");
		try {
			// eshopService.updateByObj(eshop);
			shippingService.insert(shipping);
		} catch (Exception e) {
			logger.error("EUserController.saveShipping", e);
		}
		return modelAndView;
	}

	@ResponseBody
	@RequestMapping(value = "/shops", method = RequestMethod.POST)
	public List<EShop> getShopps(@RequestBody EShop user,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("page") PageEntity page) {
		List<EShop> shopps = new ArrayList<EShop>();
		try {
			this.setPage(page);
			this.getPage().setPageSize(20);
			shopps = eshopService.searchShopps(user.getLng(), user.getLat(),
					page);
			for (EShop shop : shopps) {
				ClientInfo client = UserSessionCache.merchantSession.get(shop
						.getUserId());
				if (client == null) {
					shop.setIsOnline(CoreConstant.SHOPPER_IS_OUTLINE);
				} else {
					shop.setIsOnline(CoreConstant.SHOPPER_IS_ONLINE);
				}
			}
		} catch (Exception e) {
			logger.error("EUserController.saveShipping", e);
		}
		return shopps;
	}
}
